package com.evil.mi.task;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import com.evil.mi.dao.VideoImgRepository;
import com.evil.mi.dao.VideoRepository;
import com.evil.mi.entity.VideoEntity;
import com.evil.mi.entity.VideoImgEntity;
import com.evil.mi.enums.VideoImgStateEnum;
import com.evil.mi.enums.VideoStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * com.evil.mi.task
 *
 * @author 白雨浓
 * date: 2018/8/20 10:28
 * content:
 */
@Component
@Slf4j
public class VideoImgStateTask {

    private static Set<VideoEntity> videoSet = new ConcurrentHashSet<>();

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private VideoImgRepository videoImgRepository;

    //@Scheduled(fixedRate = 10000)
    public void handleState() {

        try {
            new Thread(this::handleFinish).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (videoSet.size() != 0) {
            log.info("任务尚未执行完成，中断此次TASK");
            return;
        }

        List<VideoEntity> videoList = videoRepository.findAll(Example.of(VideoEntity.builder().state(VideoStateEnum.DOWNLOADING).build()));

        videoSet.addAll(videoList);

        for (VideoEntity entity : videoSet) {
            List<VideoImgEntity> videoImgEntityList = videoImgRepository.findByVideoId(entity.getId());

            entity.setState(VideoStateEnum.DOWNLOADING);
            videoRepository.save(entity);

            try {
                for (VideoImgEntity imgEntity : videoImgEntityList) {
                    new Thread(() -> handleVideoImg(imgEntity)).start();
                }

                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        videoSet.clear();
    }

    private void handleFinish() {
        List<VideoEntity> videoList = videoRepository.findAll(Example.of(VideoEntity.builder().state(VideoStateEnum.DOWNLOADING).build()));

        for (VideoEntity entity : videoList) {

            List<VideoImgEntity> imgList = videoImgRepository.findByVideoId(entity.getId());

            List<VideoImgEntity> finishList = imgList.stream()
                    .filter(imgEntity -> VideoImgStateEnum.FINISH.equals(imgEntity.getState()))
                    .collect(Collectors.toList());

            if (finishList.size() == imgList.size()) {
                entity.setState(VideoStateEnum.FINISH);
                videoRepository.save(entity);
            }
        }

    }

    private void handleVideoImg(VideoImgEntity entity) {
        log.info("开始下载图片>> videoId:{}, imgUrl:{}", entity.getVideoId(), entity.getImgUrl());
        entity.setState(VideoImgStateEnum.DOWNLOADING);
        videoImgRepository.save(entity);

        String md5 = DigestUtil.md5Hex(entity.getImgUrl());

        String path = "F:/video/img/" + md5.substring(0, 2) + "/" + md5 + ".jpg";
        entity.setPath("/img/" + md5.substring(0, 2) + "/" + md5 + ".jpg");

        HttpUtil.downloadFile(entity.getImgUrl(), FileUtil.file(path));

        entity.setState(VideoImgStateEnum.FINISH);
        videoImgRepository.save(entity);
    }

}
